package stuttgart.uni.locationtracker;

import java.util.Hashtable;

public class LocationDatabase {
	
	private Hashtable<String,Predictor> database = new Hashtable<String,Predictor>();

	private Hashtable<String,String> clients;
	
	public LocationDatabase() {
		clients = new Hashtable<String,String>();
		database = new Hashtable<String,Predictor>();
	}
	
	public synchronized void addClient(TrackingData clientdata){
		clients.put(clientdata.getId(), clientdata.getUsername());
		System.out.println("Client eingelogt: "+ clientdata.getId()+ " "+ clientdata.getUsername());
		database.put(clientdata.getId(),new Predictor(clientdata));
	}
	
	public synchronized void removeClient(String id){
		System.out.println("Client ausgelogt: "+ id + " "+ clients.get(id));
		clients.remove(id);
		database.remove(id);
	}
	
	public synchronized void updateClientPosition(TrackingData newData){
		
		if(database.containsKey(newData.getId())){
			database.put(newData.getId(),new Predictor(newData));
			System.out.println("update erhalten von: "+ newData.getId()+ " "+ newData.getUsername());
		}else{
			addClient(newData);
		}
		
	}
	
	public synchronized TrackingData getClientPosition(String id){
		if(database.containsKey(id)){
			return database.get(id).getEstimatedPositionCurrently();
		}
		return null;
	}

	public synchronized FriendList getFriendList(){
		String[] ids = new String[clients.size()];
		clients.keySet().toArray(ids);
		String[] usernames = new String[clients.size()];
		clients.values().toArray(usernames);
		return new FriendList(ids,usernames);
	}
}
